package paim.wingchun.controller.eventos;


import java.awt.KeyboardFocusManager;

import javax.swing.JPanel;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;

import paim.wingchun.app.WC_App;
import paim.wingchun.controller.AbstractController;
import paim.wingchun.swing.ClipboardFix;
import paim.wingchun.view.AbstractView;

public class DefaultInternalFrameEvent implements InternalFrameListener {

    /* armazeno o controlador, para nao ter que ficar procurando sempre */
    private AbstractController<?, ?> abstractController;

    public DefaultInternalFrameEvent(AbstractController<?, ?> controlador) {
        super();
        this.abstractController = controlador;
    }

    @Override
    public void internalFrameOpened(InternalFrameEvent e) {
        // System.out.println("InternalFrameEventoOpened");
    }

    @Override
    public void internalFrameActivated(InternalFrameEvent e) {
        WC_App.getInstancia().setHasFocus((AbstractView<?>) e.getInternalFrame());

        /* mantem glasspane da janela ancestral sempre visivel, mesmo ao ser ativada */
        if ( ((JPanel) abstractController.getVisao().getGlassPane()).getComponentCount() > 0 )
            abstractController.getVisao().getGlassPane().setVisible(true);
    }

    @Override
    public void internalFrameClosing(InternalFrameEvent e) {

        if ( abstractController.getPai() != null ) {
            if ( !abstractController.getPai().getVisao().isEnabled() )
                abstractController.getPai().getVisao().setEnabled(true);
        }

        /* remove controlador da lista */
        WC_App.getControladors().remove(this.abstractController);
    }

    @Override
    public void internalFrameClosed(InternalFrameEvent e) {

        /* faz de tudo para tentar liberar memoria */
        Runnable run = new Runnable() {

            @Override
            public void run() {
                try {

                    abstractController.getVisao().removeInternalFrameListener(DefaultInternalFrameEvent.this);
                    abstractController = null;

                    if ( WC_App.getInstancia().getVisaoApp().getjDesktopPane().getAllFrames().length == 0 ) {
                        WC_App.getInstancia().setHasFocus(null);
                        KeyboardFocusManager.getCurrentKeyboardFocusManager().clearGlobalFocusOwner();
                        ClipboardFix.fixClipBoard();
                    }

                    KeyboardFocusManager.getCurrentKeyboardFocusManager().setGlobalCurrentFocusCycleRoot(null);
                    System.gc();
                }
                catch ( Exception e ) {}
            }
        };
        new Thread(run).start();
    }

    @Override
    public void internalFrameIconified(InternalFrameEvent e) {}

    @Override
    public void internalFrameDeiconified(InternalFrameEvent e) {}

    @Override
    public void internalFrameDeactivated(InternalFrameEvent e) {}
}
